var express = require('express');
var router = express.Router();
var message = require('../model/returnMessage');
var auth = require('../middleware/auth');
const busboy = require('busboy');
const fs = require('fs');
const { server } = require('../config/config.default');
const {
  setPostText,
  getNearestPost,
  getNearestPostByAuthor,
  getPostInfoById,
  getId,
  addPost,
  deletePostById,
} = require('../controller/post');
const {
  postAddedValidator,
  postEditValidator,
  postHomeNoneValidator,
  postHomeValidator,
  postSearchIDValidator,
  postPutImageValidator,
  postDeleteValidator,
} = require('../middleware/post');
const path = require('path');
const { randomID } = require('../utils/postid');

router.post('/home', [auth, postHomeValidator], getNearestPostByAuthor);

router.get('/search-id', [auth, postSearchIDValidator], getPostInfoById);

router.get('/id', [auth], getId);

router.get('/home/none', [auth, postHomeNoneValidator], getNearestPost);

router.put('/edit', [auth, postEditValidator], setPostText);

router.post('/add', [auth, postAddedValidator], addPost);

router.delete('/delete', [auth, postDeleteValidator], deletePostById);

router.put(
  '/input-image/:id',
  [auth, postPutImageValidator],
  (req, res, next) => {
    req.body.pictureID = req.params.id + '_' + randomID(3);
    const bb = busboy({ headers: req.headers });
    bb.on('file', (name, file, info) => {
      if (!/^image\/(png)|(jpeg)$/.test(info.mimeType)) {
        res.status(401).json(message({}, '.png/.jpg/.jpeg picture needed.'));
        return;
      }
      try {
        file.pipe(
          fs.createWriteStream(
            path.join(
              './public/post',
              req.params.id,
              req.body.pictureID + '.png'
            )
          )
        );
      } catch (e) {
        res.status(500).json(message({}, 'Internal server error.'));
      }
    });

    bb.on('close', () => {
      res.status(200).json(
        message(
          {
            url:
              server.baseURL +
              '/post/' +
              req.params.id +
              '/' +
              req.body.pictureID +
              '.png',
          },
          'Image created.'
        )
      );
    });

    req.pipe(bb);
    return;
  }
);

module.exports = router;
